#! /usr/bin/env node

const path = require("path");
const fs = require("fs");
const inquirer = require("inquirer");
const ejs = require("ejs");

// 接收用户输入
inquirer
  .prompt([
    {
      type: "list",
      name: "which do you want?",
      choices: ["Apple", "banana", "Peach", "strawberry"],
    },
  ])
  .then((answers) => {
    handleAnswers(answers);
  });

/**
 * 处理用户输入
 * @param {*} answers
 */
function handleAnswers(answers) {
  const tplDir = path.join(__dirname, "templates");
  const destDir = process.cwd();
  fs.readdir(tplDir, (err1, files) => {
    if (err1) throw err1;
    files.forEach((file) => {
      const sourcePath = path.join(tplDir, file);
      const destPath = path.join(destDir, file);
      renderTpl(sourcePath, destPath, { favorite: Object.values(answers)[0] });
    });
  });
}

/**
 * 渲染编译过后的模版文件
 * @param {*} sourcePath
 * @param {*} destPath
 * @param {*} answers
 */
function renderTpl(sourcePath, destPath, answers) {
  ejs.renderFile(sourcePath, answers, (err2, res) => {
    if (err2) throw err2;
    fs.writeFileSync(destPath, res);
  });
}
